//
//  NWPopWindow.m
//  NongWanCloud
//
//  Created by YueWen on 2018/4/13.
//  Copyright © 2018年 YueWen. All rights reserved.
//

#import "NWPopWindow.h"
#import "RITLKit.h"
#import <RITLViewFrame/UIView+RITLFrameChanged.h>

@implementation NWPopWindow

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:UIScreen.mainScreen.bounds]) {
        
        [self pop_buildViews];
        [self pop_addSubViews];
    }
    
    return self;
}


+ (instancetype)sharedInstance
{
    static id shareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [self new];
    });
    
    return shareInstance;
}



- (void)pop_buildViews
{
    self.backgroundColor = UIColor.clearColor;
    
    self.backgroundView = ({
        
        UIView *view = [UIView new];
        view.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.4];
        view.frame = CGRectMake(0, 0, UIScreen.mainScreen.ritl_width, UIScreen.mainScreen.ritl_height);
        
        view;
    });
    
    [self.backgroundView addUIControlHandlerTarget:self action:@selector(dismiss)];
}



- (void)pop_addSubViews
{
    [self addSubview:self.backgroundView];
}



- (UIView *)contentView
{
    return self.backgroundView;
}


#pragma mark - show - dismiss

- (void)show
{
    //获得keyWindows
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];//追加
    [self showAnimated];
}


- (void)dismiss
{
    //获得keyWindows
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    if (![keyWindow.subviews containsObject:self]) {
        
        return;
    }
    
    [self dismissAnimated];
}



+ (void)show
{
    [self show:nil];
}


+ (void)show:(id<NWPopWindowDelegate>)delegate
{
    id shareInstance = self.sharedInstance;
    
    if (![shareInstance isKindOfClass:self.class]) {
        
        return;
    }
    
    NWPopWindow *share = (NWPopWindow *)shareInstance;
    
    share.delegate = delegate;
    
    //获得keyWindows
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    //如果subViews
    if ([keyWindow.subviews containsObject:share]) {
        
        [share removeFromSuperview];
    }
    
    [share show];
}



+ (void)dimiss:(id<NWPopWindowDelegate>)delegate
{
    id shareInstance = self.sharedInstance;
    
    if (![shareInstance isKindOfClass:self.class]) {
        
        return;
    }
    
    NWPopWindow *share = (NWPopWindow *)shareInstance;
    
    share.delegate = delegate;
    [share dismiss];
}


+ (void)dismiss
{
    [self dimiss:nil];
}


// child

- (void)showAnimated {}
- (void)dismissAnimated {}


- (void)dealloc {
    NSLog(@"dealloc [%@]",NSStringFromClass(self.class));
}

@end
